package com.tanhua.manage.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.manage.constant.Constant;
import com.tanhua.manage.service.AdminService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    // 生成验证码图片
    @GetMapping("/code")
    public void verification(String uuid, HttpServletResponse response) throws IOException {

        System.err.println(uuid);

        // 生成验证码对象
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(140, 45);

        // 获取验证码
        String code = lineCaptcha.getCode();

        // 将验证码存入redis
        redisTemplate.opsForValue().set(Constant.CHECK_CODE + uuid,code);

        // 将图片返回
        lineCaptcha.write(response.getOutputStream());

    }

    // 用户登录
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map){


        // 获取请求参数
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");


        // 登录
        Map retMap = adminService.login(username,password,verificationCode,uuid);

        return ResponseEntity.ok(retMap);
    }

    @GetMapping("/verify")
    public String verify(@RequestHeader("Authorization") String token){

        try {
            // 解析token
            // Claims claims = Jwts.parser().setSigningKey("chen").parseClaimsJws(token).getBody();
            Claims claims = Jwts.parser()
                    .setSigningKey("itcast")
                    .parseClaimsJws(token)
                    .getBody();

            return "200";
        } catch (Exception e) {
            e.printStackTrace();

            return "401";
        }
    }


}
